//
//  HXDUserViewModel.swift
//  weibo
//
//  Created by huxuedong on 15/12/9.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit

class HXDStatusViewModel: NSObject {
    
    var retweetText: String = "转发"
    var commentText: String = "评论"
    var goodText: String = "赞"
    //转发微博的内容
    var retweetTextString: String?
    //来源
    var sourceText: String?
    //创建时间
    var createText: String {
        guard let createDate: NSDate = NSDate.createDate((status?.created_at)!) else {
            return ""
        }
        return createDate.createDateString
    }
    
    //引用数据模型
    var status: HXDStatus?
    //原创微博富文本
    var originalStatusAttribute: NSMutableAttributedString?
    //转发微博富文本
    var retweetedStatusAttribute: NSMutableAttributedString?
    //原创微博特殊字符
    var originalStatusSpecialString: [HXDMatchResult]?
    //转发微博特殊字符
    var retweetedStatusSpecialString: [HXDMatchResult]?
    
    //设置会员图标
    var vipImage: UIImage? {
        guard let mbrank = status?.user?.mbrank else {
            return nil
        }
        if mbrank > 0 && mbrank < 7 {
            return UIImage(named: "common_icon_membership_level\(mbrank)")
        }
        return nil
    }
    
    //认证类型： -1为没有认证，1为认证用户，2、3、5为企业认证，220为达人
    var verifiedImage: UIImage? {
        guard let verified = status?.user?.verified else {
            return nil
        }
        switch verified {
        case -1:
            return UIImage(named: "")
        case 1:
            return UIImage(named: "avatar_vip")
        case 2,3,5:
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            return UIImage(named: "avatar_grassroot")
        default:
            return nil
        }
    }
    
    //遍历构造(初始化)方法
    init(status: HXDStatus) {
        super.init()
        self.status = status
        retweetText = getText(self.status?.reposts_count ?? 0, title: "转发")
        commentText = getText(self.status?.comments_count ?? 0, title: "评论")
        goodText = getText(self.status?.attitudes_count ?? 0, title: "赞")
        
        //原创微博特殊字符串及富文本
        let result = dealWithStatusText(status.text)
        originalStatusAttribute = result.attribute
        originalStatusSpecialString = result.specialString
        
        if let retweetStatus = status.retweeted_status {
            if let name = retweetStatus.user?.name {
                retweetTextString = "@\(name):\(retweetStatus.text!)"
                //转发微博特殊字符串及富文本
                let result = dealWithStatusText(retweetTextString)
                retweetedStatusAttribute = result.attribute
                retweetedStatusSpecialString = result.specialString
            }
        }
        
        //来源字符串的格式：<a href="http://weibo.com" rel="nofollow">新浪微博</a>
        //判断来源是否存在，并且来源字符串中是否包含" "> "
        if let sourceString = status.source where sourceString.containsString("\">") {
            let startRange = sourceString.rangeOfString("\">")!
            let endRange = sourceString.rangeOfString("</")!
            sourceText = "来自 \(sourceString.substringWithRange(startRange.endIndex..<endRange.startIndex))"
        }
    }
    
    private func getText(count: Int, title: String) -> String {
        if count > 0 {
            if count < 10000 {
                return "\(count)"
            } else {
                let result = CGFloat(count / 1000) / 10
                let resultString = "\(result)万"
                //判断字符串中是否含有".0"
                if resultString.containsString(".0") {
                    //用""替换".0"
                    return resultString.stringByReplacingOccurrencesOfString(".0", withString: "")
                }
                return resultString
            }
        }
        return title
    }
    
    //传入微博内容并处理，返回一个元祖类型，元祖中包含微博内容对应的富文本和特殊字符串
    private func dealWithStatusText(statusText: String?) -> (attribute: NSMutableAttributedString?, specialString: [HXDMatchResult]?) {
        guard let text = statusText else {
            return (nil, nil)
        }
        let result = NSMutableAttributedString(string: text)
        var matchResult = [HXDMatchResult]()
        //匹配表情字符串，如[笑cry]
        //正则表达式："\\[ \\]":匹配"[]"，"\\u4e00-\\u9fa5":"匹配汉字"("\\"代表转义)
        //count：捕获到的个数，string：捕获到的结果的指针，range：捕获到的范围的指针
        //".memory"：取地址中的内容
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (count, string, range, _) -> Void in
            let match = HXDMatchResult(string: string.memory! as String, range: range.memory)
            matchResult.append(match)
        }
        //倒序遍历数组
        for match in matchResult.reverse() {
            if let emoticon = HXDEmoticonTools.sharedInstance.getEmoticonWithChs(match.string) {
                //表情附件
                let attachment = HXDTextAttachment()
                //表情富文本
                let attribute = attachment.attributeStringWithEmoticon(emoticon, font: UIFont.systemFontOfSize(textFontSize))
                //用富文本替换对应位置的表情字符串
                result.replaceCharactersInRange(match.range, withAttributedString: attribute)
            }
        }
        //特殊字符串颜色
        let specialStringColor = setSpecialStringColor(result)
        //设置字体大小
        result.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(textFontSize), range: NSMakeRange(0, result.length))
        return (result, specialStringColor)
    }
    
    private func setSpecialStringColor(attribute: NSMutableAttributedString) -> [HXDMatchResult] {
        var result = [HXDMatchResult]()
        //匹配用户昵称"@..."，包括下划线在内的任何Unicode字符集
        (attribute.string as NSString).enumerateStringsMatchedByRegex("@[\\w]+") { (_, string, range, _) -> Void in
            attribute.addAttribute(NSForegroundColorAttributeName, value: RGB(red: 80, green: 125, blue: 175), range: range.memory)
            result.append(HXDMatchResult(string: string.memory! as String, range: range.memory))
        }
        //匹配短链接"http://..."，^ \ \s：非 (转义) 任何不可见字符
        (attribute.string as NSString).enumerateStringsMatchedByRegex("http://[^\\s^\\u4e00-\\u9fa5]+") { (_, string, range, _) -> Void in
            attribute.addAttribute(NSForegroundColorAttributeName, value: RGB(red: 80, green: 125, blue: 175), range: range.memory)
            result.append(HXDMatchResult(string: string.memory! as String, range: range.memory))
        }
        //匹配话题"#...#"，"#"开头和结束，中间没有"#"
        (attribute.string as NSString).enumerateStringsMatchedByRegex("#[^#]+#") { (_, string, range, _) -> Void in
            attribute.addAttribute(NSForegroundColorAttributeName, value: RGB(red: 80, green: 125, blue: 175), range: range.memory)
            result.append(HXDMatchResult(string: string.memory! as String, range: range.memory))
        }
        return result
    }
    
    override var description: String {
        let keys = ["status"]
        return dictionaryWithValuesForKeys(keys).description
    }

}
